<?php

function P($obj,$isEnd=true){
	header("Content-type: text/html; charset=utf-8");
	echo '<pre style="margin:10px; padding:10px; border:1px #ccc solid; background-color:#f9f9f9; font-size:13px;">';
	print_r($obj);
	echo '</pre>';
	if($isEnd) exit();
}

/**
* 无限级分类排序 按级别归类
* @return
*/
function category($data,$pid='0'){
    $arr = array();
    foreach($data as $v){
        if($v['pid'] == $pid){
            $v['child'] = category($data,$v['id']);
            $arr[] = $v;    
        }
    }
    return $arr;
}
if(!function_exists('page_array')){
    /** 
     * 数组分页函数  核心函数  array_slice 
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中 
     * $count   每页多少条数据 
     * $page   当前第几页 
     * $array   查询出来的所有数组 
     * order 0 - 不变     1- 反序 
     */   
      
    function page_array($count,$page,$array,$order){  
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面   
           $start=($page-1)*$count; #计算每次分页的开始位置  
        if($order==1){  
          $array=array_reverse($array);  
        }     
        $totals=count($array);    
        $countpage=ceil($totals/$count); #计算总页面数  
        $pagedata=array();  
        $pagedata=array_slice($array,$start,$count);  
        return $pagedata;  #返回查询数据  
    } 
}
if(!function_exists('video_cover')){
    function video_cover($video){
        $video_cover = '';
        try {
            $siteurl = C("SiteUrl");
            require_once 'ThinkPHP/Library/Vendor/autoload.php';
            $ffmpeg = new \Common\Util\FFMpeg();
            $ffmpeg = $ffmpeg->ffmpeg;
            // 视频路径
            $video_path = str_replace($siteurl, './', $video);
            if(!is_file($video_path)){
                $video_path = str_replace('http://www.yuzhuli.com/', './', $video);
            }
            if(is_file($video_path)){
                $poster_path = $cover_path.md5($video_path).'.jpg';// 生成封面保存路径
                if(!is_file($poster_path)){
                    $video = $ffmpeg->open($video_path);
                    $frame = $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(1));
                    $frame->save($poster_path, false);  
                }
                $video_cover = str_replace('/./', '/', $siteurl.$poster_path);
            }
        } catch (\Exception $e) {
            trace('生成图片失败:'.$e->getMessage(), 'error');
        }
        return $video_cover;
    }
}

if(!function_exists('pushMessageToSingles')){
    function pushMessageToSingles($clientId, $msg, $content = []){
        vendor('Gtpush.Igetui');
        $igt = new \IGeTui(HOST ,APPKEY, MASTERSECRET);

        $template =  new \IGtNotificationTemplate();
        $template->set_appId(APPID);//应用appid
        $template->set_appkey(APPKEY);//应用appkey
        $template->set_transmissionType(1);//透传消息类型
        $template->set_transmissionContent($content ? json_encode($content) : '');//透传内容
        $template->set_title("娱助理");//通知栏标题
        $template->set_text($msg);//通知栏内容
        $template->set_logo("http://www.yuzhuli.com/login.png");//通知栏logo
        $template->set_isRing(true);//是否响铃
        $template->set_isVibrate(true);//是否震动
        $template->set_isClearable(true);//通知栏是否可清除

        $message = new \IGtSingleMessage();
        $message->set_isOffline(true);//是否离线
        $message->set_offlineExpireTime(3600*12*1000);//离线时间
        $message->set_data($template);//设置推送消息类型
        //接收方
        $target = new \IGtTarget();
        $target->set_appId(APPID);
        $target->set_clientId($clientId);
        
        try {
            $rep = $igt->pushMessageToSingle($message, $target);
            return ['status'=>1, 'result'=>$rep];
        }catch(\RequestException $e){
            return ['status'=>0, 'msg'=>$e->getMessage()];
        }
    }
}

/**
 * 删除目录或者文件
 * @param  string  $path
 * @param  boolean $is_del_dir
 * @return fixed
 */
function del_dir_or_file($path, $is_del_dir = FALSE) {
	
    $handle = opendir($path);
    if ($handle) { // $path为目录路径 
        while (false !== ($item = readdir($handle))) { 
            if ($item != '.' && $item != '..') {  // 除去..目录和.目录
                if (is_dir("$path/$item")) { 
                    del_dir_or_file("$path/$item", $is_del_dir);   // 递归删除目录
                } else { 
					//echo "del tfile $path/$item<br />";
                    unlink("$path/$item");  // 删除文件
                }
            }
        }
        closedir($handle);
        if ($is_del_dir) { 					
			//echo "del dir $path <br />"; 
            return rmdir($path); // 删除目录
        }
    }else {
        if (file_exists($path)) {		
			//echo "del file $path <br />"; 
            return unlink($path);
        } else {
            return false;
        }
    }
}

function gtTouser(){
	vendor('Gtpush.Igetui'); 
    $igt = new \IGeTui(NULL,APPKEY,MASTERSECRET,false); 
    $template = IGtTransmissionTemplateDemo(); 
    $message = new \IGtSingleMessage(); 
    $message->set_isOffline(true);//是否离线
    $message->set_offlineExpireTime(3600*12*1000);//离线时间
    $message->set_data($template);//设置推送消息类型  
    //接收方
    $target = new \IGtTarget();
    $target->set_appId(APPID);
    $target->set_clientId(CID);  
    try {
        $rep = $igt->pushMessageToSingle($message, $target);
		P($rep);
        var_dump($rep);
        echo ("<br><br>");

    }catch(RequestException $e){ 
        $requstId =e.getRequestId();
        $rep = $igt->pushMessageToSingle($message, $target,$requstId);
        var_dump($rep);
        echo ("<br><br>");
    }
}

/**
 * 加水印
 * @param string $filename 文件路径
 * @return mixed
 */
function Watermark($filename){
	  	 $filename = '.'.$filename;
		$finfo = pathinfo($filename);
		$exe = strtolower($finfo['extension']);//后缀名
		$exe = ($exe=='jpg')?'jpeg':$exe;
		$iSize = getimagesize($filename); //获取图片信息
		$width = $iSize[0];
		$newwidth=$width/3;//设定水印比例
		$markSize = getimagesize('./logo.png');//水印
		$imgMark = imagecreatefrompng('./logo.png');
		$s = array( $newwidth, $newwidth*$markSize[1]/$markSize[0]);
		$newMark = imagecreatetruecolor($s[0],$s[1]);//生成新的水印
		
		$alpha = imagecolorallocatealpha($newMark, 0, 0, 0, 127);//附上颜色
		imagefill($newMark, 0, 0, $alpha);
		
		imagecopyresized($newMark,$imgMark,0,0,0,0,$s[0],$s[1],$markSize[0],$markSize[1]);//裁剪
		$fn = 'imagecreatefrom'.$exe;
		$simg = $fn($filename);
		imagecopy($simg,$newMark,$iSize[0]-$s[0],$iSize[1]-$s[1],0,0,$s[0],$s[1]);//加水印
		$fn2 = 'image'.$exe;
		imagesavealpha($simg, true);//开启png透明
		
		$fn2($simg,$filename);//保存图片
		
	}

    function getAudioDuration($path)
    {
        $getID3 = new \Common\Util\getID3();    //实例化类
        $ThisFileInfo = $getID3->analyze($path); //分析文件，$path为音频文件的地址
        return $fileduration=$ThisFileInfo['playtime_seconds']; //这个获得的便是音频文件的时长
    }

    function distance_txt($distance){
        if($distance){
            // if($distance > 1000){
                return round($distance/1000, 2).'km';
            // }else{
            //     return $distance.'m';
            // }
        }else{
            return '0km';
        }
    }

    function get_comment($type, $target_id, $page = 0, $num = 20)
    {
        $model = M('comment');
		if($page){
			$list = $model->where(['type'=>$type, 'target_id'=>$target_id])->order('create_time desc,id desc')->field("id,uid,score,imgs,content,create_time as time")->page($page, $num)->select();
		}else{
			$list = $model->where(['type'=>$type, 'target_id'=>$target_id])->order('create_time desc,id desc')->field("id,uid,score,imgs,content,create_time as time")->select();
		}
		if($list){
			if($uid_arr = array_column($list, 'uid')){
				$user = M('user')->where(['id'=>['in', $uid_arr]])->getField('id,nickname,img as avatar', true);
			}else{
				$user = [];
			}
			$current_year = date('Y年');
			foreach($list as $key=>&$row){
				if(isset($user[$row['uid']])){
					$row['nickname'] = $user[$row['uid']]['nickname'];
					$row['avatar'] = $user[$row['uid']]['avatar'];
				}else{
					$row['nickname'] = '';
					$row['avatar'] = 'http://www.yuzhuli.com/Public/upload/userimg/t.jpg';
				}
                $row['score'] = round($row['score']);
				$row['imgs'] = $row['imgs'] ? explode(",", $row['imgs']) : [];
                $row['time'] = date('Y年m月d日', $row['time']);
                $row['time'] = str_replace($current_year, '', $row['time']);
			}
		}
        return $list;
    }


if(!function_exists('ptrace')){
    function ptrace($msg){
        return pubu(is_string($msg) ? $msg : '`' . var_export($msg, true) . '`', 'trace');
    }
}

if(!function_exists('pubu')){
    function pubu($text, $channel = 'trace', $name = '', $avatarUrl = '', $attachments = array()){
        try{
            $urls = array(
                'trace'       => 'https://hook.bearychat.com/=bwExa/incoming/1979f72f4a17d4e906a4cfd916412e2e',
                'trace_debug' => 'https://hook.bearychat.com/=bwExa/incoming/1979f72f4a17d4e906a4cfd916412e2e',
                'all'         => 'https://hook.bearychat.com/=bwExa/incoming/1979f72f4a17d4e906a4cfd916412e2e',
            );
            if (!isset($urls[$channel])) {
                return false;
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_URL, $urls[$channel]);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $post_data = [
                "text"=> date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']).' '.$_SERVER['SERVER_PROTOCOL'].' '.$_SERVER['REQUEST_METHOD'].' : '.PHP_EOL.$text
            ];
            $headers = [
                'Content-type: application/json',
            ];
            @curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
            $result = curl_exec($ch);
            if ($error = curl_error($ch)) {
                return false;
            }
            return true;
        }catch(\Exception $e){
            return false;
        }
    }
}
// /**
//  * 调试到瀑布使用
//  */
// function ptrace($msg)
// {
//     return pubu(is_string($msg) ? $msg : '`' . var_export($msg, true) . '`', 'chenzhi_debug');
// }

// // pubu日志
// function pubu($text, $channel = 'chenzhi', $name = '', $avatarUrl = '', $attachments = array())
// {
//     $urls = array(
//         'chenzhi'       => 'https://hooks.pubu.im/services/zvvk3gkv33xeig2',
//         'chenzhi_debug' => 'https://hooks.pubu.im/services/zvvk3gkv33xeig2',
//         'all'           => 'https://hooks.pubu.im/services/zvvk3gkv33xeig2',
//     );
//     if (!isset($urls[$channel])) {
//         return false;
//     }
//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
//     curl_setopt($ch, CURLOPT_URL, $urls[$channel]);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//     $post_data = array(
//         'text'        => PHP_EOL . date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : '  . PHP_EOL . $text,
//         'displayUser' => array(
//             'name'      => $name,
//             'avatarUrl' => $avatarUrl,
//         ),
//     );
//     if (!empty($attachments)) {
//         foreach ($attachments as $key => $attachment) {
//             $post_data['file'][] = "@{$attachment['url']}";
//         }
//     } else {
//         // $post_data = http_build_query($post_data);
//     }
//     @curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//     curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//     $result = curl_exec($ch);
//     if ($error = curl_error($ch)) {
//         return false;
//     }
//     return true;
// }



//function IGtTransmissionTemplateDemo(){
//  $template =  new \IGtTransmissionTemplate();
//  $template->set_appId(APPID);//应用appid
//  $template->set_appkey(APPKEY);//应用appkey
//  $template->set_transmissionType(1);//透传消息类型
//  $template->set_transmissionContent("测试离线ddd");//透传内容 
//  //APN高级推送
//  $apn = new IGtAPNPayload();
//  $alertmsg=new DictionaryAlertMsg();
//  $alertmsg->body="body";
//  $alertmsg->actionLocKey="ActionLockey";
//  $alertmsg->locKey="LocKey";
//  $alertmsg->locArgs=array("locargs");
//  $alertmsg->launchImage="launchimage";
////        IOS8.2 支持
//  $alertmsg->title="Title";
//  $alertmsg->titleLocKey="TitleLocKey";
//  $alertmsg->titleLocArgs=array("TitleLocArg");
//
//  $apn->alertMsg=$alertmsg;
//  $apn->badge=7;
//  $apn->sound="";
//  $apn->add_customMsg("payload","payload");
//  $apn->contentAvailable=1;
//  $apn->category="ACTIONABLE";
//  $template->set_apnInfo($apn); 
//  return $template;
//}


if(!function_exists('getIp')){
    function getIp(){
        $ip = "";
        $unknown = 'unknown'; 
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){ 
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
        }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) { 
            $ip = $_SERVER['REMOTE_ADDR']; 
        } 
        /**
         * 处理多层代理的情况
         * 或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
         */
        if (false !== strpos($ip, ',')) $ip = reset(explode(',', $ip)); 
        return $ip; 
    }
}

if(!function_exists('yzl_config')){
    function yzl_config($name){
        $arr = explode('.', $name);
        if(count($arr) > 1){
            $group = $arr[0];
            $name = $arr[1];
        }else{
            $name = $arr[0];
        }
        if($group){
            $config = M('Config')->where(['group'=>$group, 'name'=>$name])->find();
        }else{
            $config = M('Config')->where(['name' => $name])->find();
        }
        if(empty($config)){
            return '';
        }
        switch ($config['type']) {
            case 'array':
                $res = [];
                $arr = explode(PHP_EOL, $config['value']);
                foreach ($arr as $key => $value) {
                    $item_arr = explode(':',  $value);
                    if(count($item_arr) > 1){
                        $res[$item_arr[0]] = $item_arr[1];
                    }else{
                        $res[] = $item_arr[0];
                    }
                }
                break;
            default:
                $res = $config['value'];
                break;
        }
        return $res;
    }
}

if (!function_exists('list_search')) {
    function list_search($list, $condition){
        if(!is_array($list)){
            return [];
        }
        if (is_string($condition)) {
            parse_str($condition, $condition);
        }
        
        foreach($list as $key => $data){
            foreach ($condition as $field => $value) {
                if(!isset($data[$field]) || $data[$field] != $value){
                    unset($list[$key]);
                    break;
                }
            }
        }
        return $list;
    }
}

if (!function_exists('jc_member_check')) {
    function jc_member_check($info){
        if($info['member_expire'] && $info['member_expire'] >= time()){
            if($info['member_grade'] >= 1){
                return true;
            }
        }
        return false;
    }
}



if (!function_exists('toList')) {
    
    /**
     * 将数据集格式化成列表结构
     * @param  array|object   $lists 要格式化的数据集，可以是数组，也可以是对象
     * @param  integer $pid        父级id
     * @param  integer $level      级别
     * @return array 列表结构(一维数组)
     */
    function toList($lists = [], $pid = 0, $level = 0)
    {
        if (is_array($lists)) {
            $trees = [];
            foreach ($lists as $key => $value) {
                if ($value['pid'] == $pid) {
                    $title_prefix   = str_repeat("&nbsp;", $level * 4).'┝';
                    $value['level'] = $level + 1;
                    $value['title_prefix']  = $level == 0 ? '' : $title_prefix;
                    $value['title_display'] = $level == 0 ? $value['title'] : $title_prefix.$value['title'];
                    $trees[] = $value;
                    unset($lists[$key]);
                    $trees   = array_merge($trees, toList($lists, $value['id'], $level + 1));
                }
            }
            return $trees;
        } else {
            foreach ($lists as $key => $value) {
                if ($value['pid'] == $pid && is_object($value)) {
                    $title_prefix   = str_repeat("&nbsp;", $level * 4).'┝';
                    $value['level'] = $level + 1;
                    $value['title_prefix']  = $level == 0 ? '' : $title_prefix;
                    $value['title_display'] = $level == 0 ? $value['title'] : $title_prefix.$value['title'];
                    $lists->offsetUnset($key);
                    $lists[] = $value;
                    toList($lists, $value['id'], $level + 1);
                }
            }
            return $lists;
        }
    }
}

if(!function_exists('month_time')){
    /**
     * 返回某天的那月开始和结束的时间戳
     * @return   
     */
    function month_time($time = null){
        $time === null && $time = time();
        return [
            mktime(0, 0, 0, date('m', $time), 1, date('Y', $time)),
            mktime(23, 59, 59, date('m', $time), date('t', $time), date('Y', $time))
        ];
    }
}

if(!function_exists('curl_get')){
    /**
     * curl GET
     * @param    [type]     $url  [description]
     * @param    array      $data [description]
     * @return   [type]           [description]
     */
    function curl_get($url, $data = []){
        if($data){
            $url .= '?'.http_build_query($data);
        }
        // return $url;
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");  //模拟浏览器访问
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return $data;
    }
}

if(!function_exists('queryExpress')){
    /**
     * 物流
     * @author 张亚伟<1743325520@qq.com>
     * @DateTime 2018-11-19
     * @param    [type]     $postcom [description]
     * @param    [type]     $getNu   [description]
     * @return   [type]              [description]
     */
    function queryExpress($postcom , $getNu) {
        $getNu = trim($getNu);
        $url = "https://www.kuaidi100.com/query?type=".$postcom."&postid=".$getNu;
        $resp = curl_get($url);
        if (empty($resp)) {
            return array('status'=>0, 'message'=>'物流公司网络异常，请稍后查询');
        }
        $data = [];
        // 签收状态
        $state = null;
        try {
            $expres = json_decode($resp, true);
            if(!empty($expres['data'])){
                foreach ($expres['data'] as $key => $info) {
                    $data[$key]['time'] = $info['time'];
                    $data[$key]['context'] = $info['context'];
                }
            }
            if(isset($expres['state'])){
                $state = $expres['state'];
            }
        } catch (\Exception $e) {
            return array('status'=>0, 'message'=>$e->getMessage());
        }
        return array( 'status'=>1, 'state'=>$state, 'message'=>'ok','data'=> $data);
    }
}

if(!function_exists('logistics_com')){
    function logistics_com($name){
        $color_number = yzl_config('product.logistics_com');
        $arr = [];
        foreach ($color_number as $key => $value) {
            $a = explode('|', $value);
            if(count($a) >= 2){
                $a[0] = trim($a[0]);
                $a[1] = trim($a[1]);
                $a[2] = trim($a[2]);
                $arr[$a[0]] = [
                    'com'   => $a[1],// 快递100type
                    'call'  => isset($a[2]) ? $a[2] : '',// 物流电话
                ];
            }
        }
        if($arr){
            foreach ($arr as $kd_name => $com) {
                if(strrpos($name, $kd_name)!==false){
                    return $com;
                }
                if(strrpos($kd_name, $name)!==false){
                    return $com;
                }
            }
        }
        return null;
    }
}

if(!function_exists('goods_buy_price')){
    function goods_buy_price($user_id, $product_id)
    {
        
    }
}

if(!function_exists('product_discount')){
    /**
     * 商品折扣
     */
    function product_discount()
    {
        return 0.8;
    }
}

if(!function_exists('product_is_buy')){
    /**
     * 是否购买过该商品
     * @author 张亚伟<1743325520@qq.com>
     * @param
     */
    function product_is_buy($user_id, $product_id, $attr_id = '')
    {
        $product = M('product')->where(['id'=>$product_id])->find();
        if($product && $product['cid']==18){
            return false;
        }
        $user = M('user')->where(['id'=>$user_id])->find();
        return $user && $user['is_buy_tea'] ? true : false;
        // $info = M('order')->alias('o')->join('JOIN __ORDER_INFO__ oi ON o.code=oi.code')->where(['o.uid'=>$user_id, 'o.pay_status'=>1, 'oi.pid'=>$product_id])->field('o.id')->find();
        // if($info){
        //     return true;
        // }else{
        //     return false;
        // }
    }
}

if(!function_exists('yc_buy_product_check')){
    /**
     * 一元购检查
     * @author 张亚伟<1743325520@qq.com>
     * @param
     */
    function yc_buy_product_check($user_id, $product_id, $attr_id = '')
    {
        $product = M('product')->where(['id'=>$product_id])->find();
        if($product && $product['cid']==20){
            $info = M('order')->alias('o')
            ->join('JOIN __ORDER_INFO__ oi ON o.code=oi.code')
            ->join('JOIN __PRODUCT__ p ON oi.pid=p.id')
            ->where(['o.uid'=>$user_id, 'o.pay_status'=>1, 'p.cid'=>20])
            ->field('p.id')
            ->find();
            if($info){
                return true;
            }

            $info = M('cart')->alias('c')
            ->join('JOIN __PRODUCT__ p ON c.pid=p.id')
            ->where(['c.uid'=>$user_id, 'p.cid'=>20, 'p.status'=>1])
            ->field('p.id')
            ->find();
            if($info){
                return 2;
            }
        }
        return false;
    }
}

if(!function_exists('money_log')){
    /**
     * 金额记录表
     * @param    integer    $user_id   用户ID
     * @param    double     $amount    变得金额
     * @param    tinyint    $source    来源类型 1返佣，2申请提现，3提现审核失败
     * @param    integer    $source_id 相关单据ID
     * @return   array
     */
    function money_log($user_id, $amount, $source, $source_id = 0){
        if(empty($amount)){
            return ['status'=>0, 'msg'=>'amount不能为空'];
        }
        $userModel = M('user');
        $user = $userModel->where(['id'=>$user_id])->find();
        if($user){
            if($user['user_money'] + $amount < 0){
                return ['status'=>0, 'msg'=>'余额不足'];
            }
            $data = [
                'user_id'       => $user_id,
                'source'        => $source,
                'source_id'     => $source_id,
                'amount'        => $amount,
                'create_time'   => time(),
            ];
            $logModel = M('money_log');
            $res1 = $logModel->add($data);
            if($amount > 0){
                $res2 = $userModel->where(['id'=>$user_id])->setInc('user_money', $amount);
            }else{
                $res2 = $userModel->where(['id'=>$user_id])->setDec('user_money', abs($amount));
            }
            if($res1 && $res2){
                return ['status'=>1, 'msg'=>'ok'];
            }else{
                return ['status'=>0, 'msg'=>'操作失败'];
            }
        }
        return ['status'=>0, 'msg'=>'用户不存在'];
    }
}

if(!function_exists('withdrawals_bank_codes')){
    /**
     * 微信银行卡
     * @return array
     */
    function withdrawals_bank_codes()
    {
        $bank_codes = yzl_config('withdrawals.withdrawals_bank_codes');
        $arr = [];
        if($bank_codes){
            foreach ($bank_codes as $key => $val) {
                $val = explode('|', $val);
                if(count($val) == 2){
                    $arr[trim($val[1])] = trim($val[0]);
                }
            }
        }
        return $arr;
    }
}

if(!function_exists('pay_bank')){
    /**
     * 微信付款到银行卡
     * @param    string     $source        来源类型
     * @param    int        $source_id     来源id
     * @param    string     $bank_code     收款方银行卡所在开户行编号
     * @param    string     $enc_bank_no   收款方银行卡号
     * @param    string     $enc_true_name 收款方用户名
     * @param    int        $amount        付款金额：RMB分（支付总额，不含手续费）注：大于0的整数
     * @return   array
     */
    function pay_bank($source, $source_id, $bank_code, $enc_bank_no, $enc_true_name, $amount){
        $trade_no = date('YmdHis').rand(10000, 99999);
        $data = [
            'source'        => $source,
            'source_id'     => $source_id,
            'trade_no'      => $trade_no,
            'bank_code'     => $bank_code,
            'enc_bank_no'   => $enc_bank_no,
            'enc_true_name' => $enc_true_name,
            'amount'        => $amount,
            'status'        => 1,
            'create_time'   => time(),
        ];

        $model = M('pay_bank');
        $id = $model->add($data);
        if(!$id){
            return ['status'=>0, 'msg'=>'失败'];
        }
        $desc = '调试';
        Vendor("Pay.Wxpay.WxPayHelper");
        $config = C('wechat');
        $WxPayHelper = new \WxPayHelper($config);
        $response = $WxPayHelper->pay_bank($trade_no, $enc_bank_no, $enc_true_name, $bank_code, $amount, $desc);
        $err_msg = '失败';
        if($response){
            if($response['return_code'] == 'SUCCESS'){
                if($response['result_code'] == 'SUCCESS'){
                    $model->where(['id'=>$id])->save(['status'=>2, 'msg'=>'ok']);
                    return ['status'=>1, 'msg'=>'ok'];
                }else{
                    $err_msg = $response['err_code_des'];
                    $model->where(['id'=>$id])->save(['status'=>3, 'msg'=>$response['err_code_des']]);
                }
            }else{
                $err_msg = $response['return_msg'];
                $model->where(['id'=>$id])->save(['status'=>3, 'msg'=>$response['return_msg']]);
            }
        }else{
            $model->where(['id'=>$id])->save(['status'=>3, 'msg'=>'请求失败']);
        }
        return ['status'=>0, 'msg'=>$err_msg];
    }
}


if(!function_exists('user_reg')){
    function user_reg($userData, $parent_no = ''){
        if(!isset($userData['phone'])){
            return false;
        }
        $userModel = M('user');
        $has = $userModel->where(array('phone'=>$userData['phone']))->find();
        if(empty($has)){
            $userModel->startTrans();
            try{
                $user_id = $userModel->add($userData);
                $to = M('token')->where('uid="' . $user_id . '"')->find();
                $info = array('uid' => $user_id, "token" => md5($user_id));
                if ($to) {
                    M('token')->where(array('id'=>$to['id']))-> save($info);
                } else {
                    M('token')->add($info);
                }
                
                $parent_no = $parent_no ? $parent_no : yzl_config('distribution.distribution_member_no');
                if($parent_no){
                    $update_user = [];
                    $parent_member = M('member_no')->where(['member_no'=>$parent_no])->find();
                    if($parent_member){
                        $parent_user = $userModel->where(['id'=>$parent_member['user_id']])->find();
                        if($parent_user){
                            $update_user['first_leader'] = $parent_user['id'];
                            if($parent_user['first_leader']){
                                $update_user['second_leader'] = $parent_user['first_leader'];
                            }
                        }
                    }
                    if($update_user){
                        $userModel->where(['id'=>$user_id])->save($update_user);
                        $offline_num = $userModel->where(['first_leader'=>$update_user['first_leader']])->count();
                        $userModel->where(['id'=>$update_user['first_leader']])->save(['offline_num'=>$offline_num, 'offline_time'=>time()]);
                    }
                }
                $member_no = M('member_no')->max('member_no');
                M('member_no')->add([
                    'user_id'       => $user_id,
                    'member_no'     => $member_no+1,
                    'create_time'   => time(),
                ]);
                $userModel->commit();
                return $user_id;
            } catch (\Exception $e) {
                $userModel->rollback();
                return false;
            }
        }else{
            return false;
        }
    }
}

if(!function_exists('uploadVideo')){
    /**
     * 上传视频
     * @param    array      $video      upload file文件
     * @param    integer    $compress   压缩
     * @param    integer    $time_limit 时间限制
     * @return   array
     */
    function uploadVideo($video, $compress = 1, $time_limit = -1)
    {
        if($compress == 1 || $time_limit!=-1){
            require_once 'ThinkPHP/Library/Vendor/autoload.php';
            $ffmpeg = new \Common\Util\FFMpeg();
            $videoInfo = $ffmpeg->video_info($video['tmp_name']);
            if(!$videoInfo['status']){
                is_file($video['tmp_name']) && unlink($video['tmp_name']);
                return ['status' => false, 'msg' => $videoInfo['msg']];
            }
            // 时长
            if($time_limit!=-1){
                $duration = $videoInfo['format']->get('duration');
                if($duration > $time_limit){
                    is_file($video['tmp_name']) && unlink($video['tmp_name']);
                    return ['status' => false, 'msg' => "时间超过{$time_limit}秒"];
                }
            }
            // 大小
            $size = $videoInfo['format']->get('size');
        }
        switch ($compress) {
            case 1:
                $width = $videoInfo['info']['width'];
                $height = $videoInfo['info']['height'];
                // 判断有没有旋转
                if(!empty($videoInfo['info']['tags']) && isset($videoInfo['info']['tags']['rotate'])){
                    switch ($videoInfo['info']['tags']['rotate']) {
                        case '90':
                        case '270':
                            $width = $videoInfo['info']['height'];
                            $height = $videoInfo['info']['width'];
                            break;
                        default:
                            break;
                    }
                }
                $max_width = 720;
                $max_height = 1280;
                // 是否需要进行缩放处理
                $is_scale = true;
                if($width > $max_width){
                    $scale = $max_width/$width;
                    $height = $height*($max_width/$width);
                    $width = $max_width;
                }else if($height > $max_height){
                    $scale = $max_height/$height;
                    $width = $width*($max_height/$height);
                    $height = $max_height;
                }else{
                    $is_scale = false;
                }
                if($is_scale){
                    // 宽高必须是2的倍数
                    $width%2 != 0 && $width++;
                    $height%2 != 0 && $height++;
                }
                // 文件MimeType
                $finfo = finfo_open(FILEINFO_MIME);
                $mimetype = finfo_file($finfo, $video['tmp_name']);
                finfo_close($finfo);
                // 是否需要转码出来
                $is_vcodec = true;
                if(stripos($mimetype, 'mp4')){
                    $is_vcodec = false;
                }
                // if($is_vcodec || $is_scale){
                    // // 后缀名
                    // $extension = pathinfo($video['name'], PATHINFO_EXTENSION);
                    // 新增文件名
                    $file_name = 'php'.date('YmdHis').rand(10000, 99999).'.mp4';
                    $tmp_name = sys_get_temp_dir().'/'.$file_name;
                    // 视频转码和压缩
                    $commands = [];
                    $commands[] = '-i';
                    $commands[] = $video['tmp_name'];
                    if($is_vcodec){
                        $commands[] = '-vcodec';
                        $commands[] = 'libx264';
                        $commands[] = '-acodec';
                        $commands[] = 'copy';
                        $commands[] = '-b:v';// 码率
                        $commands[] = '500k';// 码率值
                    }
                    if($is_scale){
                        // $commands[] = '-s';
                        // $commands[] = "{$width}x{$height}";
                        $commands[] = '-vf';
                        // $commands[] = "scale=iw/{$scale}:ih/{$scale}";
                        $commands[] = "scale={$width}:{$height}";//缩放
                    }
                    $commands[] = $tmp_name;
                    $commandRes = $ffmpeg->command($commands);
                    if(!$commandRes['status']){
                        is_file($video['tmp_name']) && unlink($video['tmp_name']);
                        return ['status' => false, 'msg' => $commandRes['msg']];
                    }
                    is_file($video['tmp_name']) && unlink($video['tmp_name']);
                // }else{
                //     $file_name = isset($video['name']) ? $video['name'] : date('YmdHis').rand(10000, 99999).'.mp4';
                //     $tmp_name = $video['tmp_name'];
                // }
                $video['name'] = $file_name;
                $video['type'] = 'video/mp4';
                $video['size'] = filesize($tmp_name);
                $video['tmp_name'] = $tmp_name;
                break;
            default:
                break;
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   = 5242880;// 设置附件上传大小
        $upload->exts      = array('mp4', 'mkv');// 设置附件上传类型
        $upload->rootPath  = './'.C('UPLOAD_PATH').'/videos/'; // 设置附件上传根目录
        $upload->savePath  = ''; // 设置附件上传（子）目录
        // 上传文件 
        $info   =   $upload->isTest(true)->upload([$video]);
        is_file($video['tmp_name']) && unlink($video['tmp_name']);
        if(!$info) {// 上传错误提示错误信息
            return ['status' => false, 'msg' => $upload->getError()];
        }
        $info = $info[0];
        $info['path'] = C('UPLOAD_PATH').'/videos/'.$info['savepath'].$info['savename'];
        return ['status' => true, 'msg' => 'ok', 'info'=>$info];
    }
}

if(!function_exists('getMimes')){
    function getMimes(){
        return array (
            //applications
            'ai'  => 'application/postscript',
            'eps'  => 'application/postscript',
            'exe'  => 'application/octet-stream',
            'doc'  => 'application/vnd.ms-word',
            'xls'  => 'application/vnd.ms-excel',
            'ppt'  => 'application/vnd.ms-powerpoint',
            'pps'  => 'application/vnd.ms-powerpoint',
            'pdf'  => 'application/pdf',
            'xml'  => 'application/xml',
            'odt'  => 'application/vnd.oasis.opendocument.text',
            'swf'  => 'application/x-shockwave-flash',
            // archives
            'gz'  => 'application/x-gzip',
            'tgz'  => 'application/x-gzip',
            'bz'  => 'application/x-bzip2',
            'bz2'  => 'application/x-bzip2',
            'tbz'  => 'application/x-bzip2',
            'zip'  => 'application/zip',
            'rar'  => 'application/x-rar',
            'tar'  => 'application/x-tar',
            '7z'  => 'application/x-7z-compressed',
            // texts
            'txt'  => 'text/plain',
            'php'  => 'text/x-php',
            'html' => 'text/html',
            'htm'  => 'text/html',
            'js'  => 'text/javascript',
            'css'  => 'text/css',
            'rtf'  => 'text/rtf',
            'rtfd' => 'text/rtfd',
            'py'  => 'text/x-python',
            'java' => 'text/x-java-source',
            'rb'  => 'text/x-ruby',
            'sh'  => 'text/x-shellscript',
            'pl'  => 'text/x-perl',
            'sql'  => 'text/x-sql',
            // images
            'bmp'  => 'image/x-ms-bmp',
            'jpg'  => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif'  => 'image/gif',
            'png'  => 'image/png',
            'tif'  => 'image/tiff',
            'tiff' => 'image/tiff',
            'tga'  => 'image/x-targa',
            'psd'  => 'image/vnd.adobe.photoshop',
            //audio
            'mp3'  => 'audio/mpeg',
            'mid'  => 'audio/midi',
            'ogg'  => 'audio/ogg',
            'mp4a' => 'audio/mp4',
            'wav'  => 'audio/wav',
            'wma'  => 'audio/x-ms-wma',
            'amr' => 'audio/amr',
            'speex' => 'audio/speex',
            // video
            'avi'  => 'video/x-msvideo',
            'dv'  => 'video/x-dv',
            'mp4'  => 'video/mp4',
            'mpeg' => 'video/mpeg',
            'mpg'  => 'video/mpeg',
            'mov'  => 'video/quicktime',
            'wm'  => 'video/x-ms-wmv',
            'flv'  => 'video/x-flv',
            'mkv'  => 'video/x-matroska'
        );
    }
}


if(!function_exists('randomStr')){
    /**
     * 方法一：获取随机字符串
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string 随机字符串
     */
    function randomStr($length = 6, $type = 'string', $convert = 0){
        $config = array(
            'number'    => '1234567890',
            'letter'    => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'nl'        => '1234567890abcdefghijklmnopqrstuvwxyz',
            'string'    => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all'       => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if (isset($config[$type])){
            $string = $config[$type];
        }else{
            $string = $type;
        }

        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string{mt_rand(0, $strlen)};
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }
}

if(!function_exists('isMobile')){
    /**
     * 是否移动端访问
     * @return   boolean                [description]
     */
    function isMobile(){
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])){
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])){
            $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])){
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
                return true;
            }
        }
        return false;
    } 
}

if(!function_exists('img_orientation_bug')){
    function img_orientation_bug($filename){
        try{
            require_once VENDOR_PATH.'autoload.php';
            $image = imagecreatefromstring(file_get_contents($filename));
            $reader = \PHPExif\Reader\Reader::factory(\PHPExif\Reader\Reader::TYPE_NATIVE);
            // $exif = exif_read_data($filename, 'THUMBNAIL');
            $exif = $reader->read($filename);
            if($exif){
                if(!empty($exif->getData()['Orientation'])) {
                    switch($exif->getData()['Orientation']) {
                        case 8:
                            $image = imagerotate($image,90,0);
                            imagejpeg($image, $filename);
                        break;
                        case 3:
                            $image = imagerotate($image,180,0);
                            imagejpeg($image, $filename);
                        break;
                        case 6:
                            $image = imagerotate($image,-90,0);
                            imagejpeg($image, $filename);
                        break;
                    }
                }
            }
        }catch(\Exception $e){
            
        }
    }
}